package com.rcoming.main;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CompoundButton;

import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.holder.StringHolder;
import com.mikepenz.materialdrawer.interfaces.OnCheckedChangeListener;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.ExpandableBadgeDrawerItem;
import com.mikepenz.materialdrawer.model.ExpandableDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.SectionDrawerItem;
import com.mikepenz.materialdrawer.model.SwitchDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.mikepenz.materialdrawer.model.interfaces.Nameable;
import com.rcoming.R;
import com.rcoming.activity.AboutActivity;
import com.rcoming.activity.CollectionActivity;
import com.rcoming.activity.CompanyProfileActivity;
import com.rcoming.activity.HistoryActivity;
import com.rcoming.activity.LoginActivity;
import com.rcoming.activity.SettingActivity;
import com.rcoming.activity.VIPActivity;
import com.rcoming.base.BaseActivity;
import com.rcoming.fragment.FirstFragment;
import com.rcoming.fragment.SecondFragment;
import com.rcoming.util.MyLogUtil;
import com.rcoming.util.SPUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity {

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.coordinatorLayout)
    CoordinatorLayout coordinatorLayout;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    private String[] tabTitleArray = {"热映电影", "走进瑞聪", "了解瑞聪", "关于瑞聪", "公司介绍"};
    private AdapterFragment adapter;
    private List<Fragment> fragments = new ArrayList<>();

    //save our header or result
    private AccountHeader headerResult = null;
    private Drawer result = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 判断是否已登陆
        loginAction();
        // 若果已经登录，正常显示
        initViews(savedInstanceState);
    }

    // 判断是否登录，动作
    private void loginAction() {
        if (!isLogin()) {
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            finish();
            return;
        }
    }

    // 初始化页面及控件
    private void initViews(Bundle saved) {

        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        toolbar.setTitle("瑞聪科技");

        fragments.add(new FirstFragment());
        fragments.add(new SecondFragment());

        for (int i = 0; i < tabTitleArray.length; i++) {
            tabLayout.addTab(tabLayout.newTab().setText(tabTitleArray[i]));
        }

        adapter = new AdapterFragment(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);

        /**
         * 设置抽屉菜单
         */

        // 创建用户
        final IProfile profile = new ProfileDrawerItem().withName("陈成").withEmail("wistorm@mail.com").withIcon("https://avatars3.githubusercontent.com/u/1476232?v=3&s=460").withIdentifier(100);
        final IProfile profile2 = new ProfileDrawerItem().withName("王伟").withEmail("Mr.Wang@github.com").withIcon(Uri.parse("https://avatars3.githubusercontent.com/u/887462?v=3&s=460")).withIdentifier(101);
        final IProfile profile3 = new ProfileDrawerItem().withName("老王").withEmail("OldWang@sina.com").withIcon(R.drawable.header1).withIdentifier(102);

        // 创建账户头
        headerResult = new AccountHeaderBuilder()
                .withActivity(this)
                .withTranslucentStatusBar(true)
                .withHeaderBackground(R.drawable.header)
                .addProfiles(
                        profile,
                        profile2,
                        profile3,
                        //don't ask but google uses 14dp for the add account icon in gmail but 20dp for the normal icons (like manage account)
                        new ProfileSettingDrawerItem().withName("添加账户").withIcon(R.mipmap.logo_round/*new IconicsDrawable(this, GoogleMaterial.Icon.gmd_plus).actionBar().paddingDp(5).colorRes(R.color.material_drawer_primary_text)*/).withIdentifier(100000),
                        new ProfileSettingDrawerItem().withName("管理账户").withIcon(R.mipmap.logo_round).withIdentifier(100001)
                )
                .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
                    @Override
                    public boolean onProfileChanged(View view, IProfile profile, boolean current) {
                        //sample usage of the onProfileChanged listener
                        //if the clicked item has the identifier 1 add a new profile ;)
                        if (profile instanceof IDrawerItem && profile.getIdentifier() == 100000) {
                            int count = 100 + headerResult.getProfiles().size() + 1;
                            IProfile newProfile = new ProfileDrawerItem().withNameShown(true).withName("Batman" + count).withEmail("batman" + count + "@gmail.com").withIcon(R.drawable.header3).withIdentifier(count);
                            if (headerResult.getProfiles() != null) {
                                //we know that there are 2 setting elements. set the new profile above them ;)
                                headerResult.addProfile(newProfile, headerResult.getProfiles().size() - 2);
                            } else {
                                headerResult.addProfiles(newProfile);
                            }
                        }

                        //false if you have not consumed the event and it should close the drawer
                        return false;
                    }
                })
                .withSelectionListEnabledForSingleProfile(false)
                .withSavedInstance(saved)
                .build();

        // 创建抽屉，侧滑菜单
        result = new DrawerBuilder()
                .withActivity(this)
                .withToolbar(toolbar)
                .withHasStableIds(true)
                .withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header
                .addDrawerItems(
                        new PrimaryDrawerItem().withName("公司介绍").withIcon(R.mipmap.logo_round).withIdentifier(1).withSelectable(false),
                        new PrimaryDrawerItem().withName("企业文化").withIcon(R.mipmap.logo_round).withIdentifier(2).withSelectable(false),
                        new PrimaryDrawerItem().withName("员工风采").withIcon(R.mipmap.logo_round).withIdentifier(3).withSelectable(false),
                        new PrimaryDrawerItem().withName("招贤纳士")/*.withDescription("查看历史记录.")*/.withIcon(R.mipmap.logo_round).withIdentifier(4).withSelectable(false)/*.withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_red_700))*/,
//                        new PrimaryDrawerItem().withName("主题选择").withIcon(R.mipmap.logo_round).withIdentifier(5).withSelectable(false),

                        new SectionDrawerItem().withName("更多功能"),
                        new ExpandableBadgeDrawerItem().withName("设置与帮助").withIcon(R.mipmap.logo_round).withIdentifier(18).withSelectable(false)/*.withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_red_700))*//*未读信息.withBadge("100")*/.withSubItems(
                                new SecondaryDrawerItem().withName("设置").withLevel(2).withIcon(R.mipmap.logo_round).withIdentifier(2000),
                                new SecondaryDrawerItem().withName("帮助").withLevel(2).withIcon(R.mipmap.logo_round).withIdentifier(2001)
                        ),
                        new ExpandableDrawerItem().withName("分享给好友").withIcon(R.mipmap.logo_round).withIdentifier(19).withSelectable(false).withSubItems(
                                new SecondaryDrawerItem().withName("QQ").withLevel(2).withIcon(R.mipmap.logo_round).withIdentifier(2002),
                                new SecondaryDrawerItem().withName("微信").withLevel(2).withIcon(R.mipmap.logo_round).withIdentifier(2003),
                                new SecondaryDrawerItem().withName("朋友圈").withLevel(2).withIcon(R.mipmap.logo_round).withIdentifier(2004),
                                new SecondaryDrawerItem().withName("QQ空间").withLevel(2).withIcon(R.mipmap.logo_round).withIdentifier(2005)
                        ),
                        new ExpandableDrawerItem().withName("关于").withIcon(R.mipmap.logo_round).withIdentifier(20).withSelectable(false).withSubItems(
                                new SecondaryDrawerItem().withName("版本更新").withLevel(2).withIcon(R.mipmap.logo_round).withIdentifier(2006),
                                new SecondaryDrawerItem().withName("关于应用").withLevel(2).withIcon(R.mipmap.logo_round).withIdentifier(2007)
                        ),
                        new DividerDrawerItem(),

                        new PrimaryDrawerItem().withName("主题选择").withIcon(R.mipmap.logo_round).withIdentifier(5).withSelectable(false),
                        new SwitchDrawerItem().withName("消息通知").withIcon(R.mipmap.logo_round).withChecked(true).withOnCheckedChangeListener(onCheckedChangeListener),
                        new SwitchDrawerItem().withName("WIFI下观看").withIcon(R.mipmap.logo_round).withChecked(true).withOnCheckedChangeListener(onCheckedChangeListener).withSelectable(false)

                )
                // 添加Item点击事件
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {

                        if (drawerItem != null) {
                            Intent intent = null;
                            if (drawerItem.getIdentifier() == 1) {
                                intent = new Intent(MainActivity.this, CompanyProfileActivity.class);
                            } else if (drawerItem.getIdentifier() == 2) {
                                intent = new Intent(MainActivity.this, VIPActivity.class);
                            } else if (drawerItem.getIdentifier() == 3) {
                                intent = new Intent(MainActivity.this, CollectionActivity.class);
                            } else if (drawerItem.getIdentifier() == 4) {
                                intent = new Intent(MainActivity.this, HistoryActivity.class);
                            } else if (drawerItem.getIdentifier() == 5) {
                                intent = new Intent(MainActivity.this, SettingActivity.class);
                            } else if (drawerItem.getIdentifier() == 2007) {
                                intent = new Intent(MainActivity.this, AboutActivity.class);
                            }

                            if (intent != null) {
                                MainActivity.this.startActivity(intent);
                            }
                        }

                        if (drawerItem instanceof Nameable) {
                            toolbar.setTitle(((Nameable) drawerItem).getName().getText(MainActivity.this));
                        }

                        return false;
                    }
                })
                .withSavedInstance(saved)
                .build();

        //only set the active selection or active profile if we do not recreate the activity
        if (saved == null) {
            // set the selection to the item with the identifier 11
            result.setSelection(21, false);

            //set the active profile
            headerResult.setActiveProfile(profile);
        }

        // 更新显示当前Item信息数量
//        result.updateBadge(4, new StringHolder(10 + ""));
        result.updateName(1, new StringHolder("随便点"));

    }

    // 切换监听
    private OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(IDrawerItem drawerItem, CompoundButton buttonView, boolean isChecked) {
            if (drawerItem instanceof Nameable) {
                MyLogUtil.d("DrawerItem: " + ((Nameable) drawerItem).getName() + " - toggleChecked: " + isChecked);
            } else {
                MyLogUtil.d("toggleChecked: " + isChecked);
            }
        }
    };

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //add the values which need to be saved from the drawer to the bundle
        outState = result.saveInstanceState(outState);
        //add the values which need to be saved from the accountHeader to the bundle
        outState = headerResult.saveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        //handle the back press :D close the drawer first and if the drawer is closed close the activity
        if (result != null && result.isDrawerOpen()) {
            result.closeDrawer();
        } else {
            super.onBackPressed();
        }
    }

    // 判断是否是已登录状态
    public boolean isLogin() {

        MyLogUtil.d("" + SPUtil.getString(context, "tokenId"));

        if (SPUtil.getString(context, "tokenId") != null) {
            return true;
        }

        return false;
    }


    public class AdapterFragment extends FragmentPagerAdapter {
        private List<Fragment> mFragments;

        public AdapterFragment(FragmentManager fm, List<Fragment> mFragments) {
            super(fm);
            this.mFragments = mFragments;
        }

        @Override
        public Fragment getItem(int position) {//必须实现
            return mFragments.get(position);
        }

        @Override
        public int getCount() {//必须实现
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {//选择性实现
            return /*mFragments.get(position).getClass().getSimpleName()*/tabTitleArray[position];
        }
    }

}

































